/**
 * 
 */
package com.armail.server.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.armail.server.dao.DBUtility;
import com.armail.server.dao.MailDAO;
import com.armail.server.domain.Mail;
import com.armail.server.domain.User;

/**
 * @author Arpit.Rathore
 *
 */
public class MailDAOImpl implements MailDAO {
	
	private SessionFactory sessionFactory = DBUtility.getSessionFactory();
	private static MailDAO mailDAO;
	
	private MailDAOImpl() {
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Mail> getMailsByUser(User user) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Mail.class);
		crit.add(Restrictions.eq("owner", user));
		crit.addOrder(Order.desc("recievedDate"));
		return crit.list();
	}
	
	@Override
	public Mail createMail(Mail mail) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Mail createdMail = (Mail) session.merge(mail);
		session.getTransaction().commit();
		session.close();
		return createdMail;
	}
	
	public static MailDAO getInstance() {
		if(mailDAO == null) {
			mailDAO = new MailDAOImpl();
		}
		return mailDAO;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Mail> getSentItemsByUser(User user) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Mail.class);
		crit.add(Restrictions.eq("fromUser", user));
		crit.add(Restrictions.eq("isDraft", false));
		crit.addOrder(Order.desc("recievedDate"));
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Mail> getDraftMailsByUser(User user) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Mail.class);
		crit.add(Restrictions.eq("fromUser", user));
		crit.add(Restrictions.eq("isDraft", true));
		crit.addOrder(Order.desc("recievedDate"));
		return crit.list();
	}
}
